package cn.cvs.controller.supplier;

import cn.cvs.controller.sysUser.SysUserController;
import cn.cvs.pojo.Supplier;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.supplier.SupplierService;
import cn.cvs.utils.Constants;
import cn.cvs.utils.PageSupport;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/supplier")
public class SupplierController {

    private Logger logger = Logger.getLogger(SysUserController.class);

    @Autowired
    private SupplierService supplierService;

    //查询供货商列表
    @RequestMapping("/list")
    public String supplierList(Model model,String querySupName,String querySupCode,@RequestParam(defaultValue = "1")Integer pageIndex){
        logger.debug("查询供货商记录");
        List<Supplier> supplierList = null;
        try {
            //设置页面总容量
            int pageSize = Constants.pageSize;
            //总记录(表)
            int totalCount = supplierService.selectCount(querySupName,querySupCode);
            //总页数
            PageSupport pageSupport = new PageSupport();
            pageSupport.setCurrentPageNo(pageIndex);
            pageSupport.setPageSize(pageSize);
            pageSupport.setTotalCount(totalCount);
            int totalPageCount = pageSupport.getTotalPageCount();
            //控制首页和尾页
            if(pageIndex > totalPageCount){
                pageIndex = totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            supplierList = supplierService.selectList(querySupName,querySupCode,pageIndex,pageSize);
            model.addAttribute("supplierList",supplierList);
            model.addAttribute("querySupCode",querySupCode);
            model.addAttribute("querySupName",querySupName);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.debug("供货商列表接口访问失败");
            return "redirect:/user/toSysError";
        }
        return "supplier/list";
    }

    //跳转到供货商添加页面
    @GetMapping("/toAdd")
    public String toAdd(){
        return "supplier/add";
    }

    //添加供货商信息
    @PostMapping("/add")
    public String add(Supplier supplier, HttpSession session, HttpServletRequest request, @RequestParam(value = "attachs",required = false) MultipartFile[] attachs) throws Exception {
        String idPicPath = null;
        String workPicPath = null;
        String errorInfo = null;
        boolean flag = true;
        String path = request.getSession().getServletContext().getRealPath("statics" + File.separator + "uploadfiles");
        logger.info("文件存储路径:" + path);
        for (int i = 0; i < attachs.length; i++) {
            MultipartFile attach = attachs[i];
            if (!attach.isEmpty()) {
                if (i == 0) {
                    errorInfo = "uploadFileError";
                } else if (i == 1) {
                    errorInfo = "uploadWpError";
                }
                String oldFileName = attach.getOriginalFilename();//原文件名
                logger.info("原文件名为:" + oldFileName);
                String prefix = FilenameUtils.getExtension(oldFileName);
                logger.debug("原文件后缀名为:" + prefix);
                int filesize = 500000;
                logger.debug("文件大小:" + attach.getSize());
                if (attach.getSize() > filesize) {
                    //上传大小不得超过500kb
                    request.setAttribute("uploadFileError", "*上传大小不得超过500KB");
                    flag = false;
                } else if (prefix.equalsIgnoreCase("jpg") || prefix.equalsIgnoreCase("png") || prefix.equalsIgnoreCase("jpeg") || prefix.equalsIgnoreCase("pneg")) {
                    //上次图片格式正确
                    String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal." + prefix;
                    logger.debug("新文件名称为:" + fileName);
                    File targetFile = new File(path);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                    }
                    //保存
                    try {
                        attach.transferTo(new File(targetFile, fileName));
                    } catch (Exception e) {
                        e.printStackTrace();
                        request.setAttribute("errorInfo", "*上传失败！");
                        flag = false;
                    }
                    if (i == 0) {
                        idPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    } else if (i == 1) {
                        workPicPath = File.separator + "statics" + File.separator + "uploadfiles" + File.separator + fileName;
                    }
                    logger.debug("idPicPath" + idPicPath);
                    logger.debug("workPicPath" + workPicPath);
                } else {
                    request.setAttribute(errorInfo, "*上传图片格式不正确");
                    flag = false;
                }
            }
        }

        if (flag) {
            supplier.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
            supplier.setCreatedTime(new Date());
            supplier.setIdPicPath(idPicPath);
            supplier.setWorkPicPath(workPicPath);
            if (supplierService.add(supplier)>0) {
                return "redirect:/supplier/list";
            }
        }
        return "supplier/add";
    }

    //根据ID查询供货商信息
    @GetMapping("/view/{id}")
    public String view(@PathVariable String id,Model model) throws Exception{
        logger.debug("根据ID查询供货商信息");
        Supplier supplier = supplierService.selectById(Integer.parseInt(id));
        model.addAttribute(supplier);
        return "supplier/view";
    }

    //跳转到修改供货商页面
    @GetMapping("/toUpdate")
    public String toUpdate(Model model,@RequestParam Integer supId) throws Exception{
        logger.debug("跳转到供货商修改页面");
        Supplier supplier = supplierService.selectById(supId);
        model.addAttribute(supplier);
        return "supplier/update";
    }

    //修改供货商信息
    @PostMapping("/update")
    public String update(Supplier supplier,HttpSession session) throws Exception{
        logger.debug("修改供货商信息");
        supplier.setUpdatedUserId(((SysUser)session.getAttribute(Constants.USER_SESSION)).getId());
        supplier.setUpdatedTime(new Date());
        if(supplierService.update(supplier) == 1){
            return "redirect:/supplier/list";
        }
        return "supplier/update";
    }

    //删除供货商信息
    @ResponseBody
    @DeleteMapping("/del/{id}")
    public Object del(@PathVariable(value = "id")Integer id,HttpSession session) throws Exception {
        logger.debug("删除供货商信息");
        HashMap<String,Object> map = new HashMap<>();
        if(supplierService.deleteById(id,session.getServletContext()) == 1){
            map.put("delResult","true");
        }else{
            map.put("delResult","false");
        }
        return map;
    }
}
